<script setup>
import {ref,reactive,watch,onMounted} from 'vue';
import {read,save as autoSave} from '@/hooks/localText';
import { useRouter } from "vue-router";
import {update} from '@/utils/note';
import addmessage from '@/hooks/message.js'
const router = useRouter();
const id = Number(router.currentRoute.value.params.id);//用于获取文本的id

onMounted(()=>{
    if(id!==0){
        text.value = sessionStorage.getItem('editText')
    }
})

let text=ref(read()??'');
//返回上一页bar
let backBar={
    home:{
        title:'主页',
        icon: 'icon-home',
        action(){
            router.push('/home')
        }
    },
}

//自动保存到本地
let isChange=false;
watch(text,()=>{
    isChange=true;
})
setInterval(()=>{
    if(isChange){
        autoSave(text.value);
        isChange=false;
    }
},10*1000);


//保存到服务器
async function save(text, html){
    // text=> 源文本文件,html=>html结构
    // console.log(text,html);
    //解析title
    const firstLineIndex=text.indexOf('\n')
    const title=text.slice(2,firstLineIndex);
    const desc=text.slice(firstLineIndex,firstLineIndex+100)+'...';
    let res=await update({
                            id:id===0?null:id,
                            title,
                            desc,
                            text,
                        });
    if(res.code==0){
        addmessage('保存成功');
        localStorage.removeItem('input');
        router.push('/home');
        return;
    }
    addmessage('发布失败',0)
}

function handleUploadImage(event, insertImage, files) {
    console.log(files);
    //插入图片
    // insertImage({
    //     url:
    //       'https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=1269952892,3525182336&fm=26&gp=0.jpg',
    //     desc: '七龙珠',
    //     // width: 'auto',
    //     // height: 'auto',
    // });
}
</script>

<template>
    <v-md-editor v-model="text" height="100vh"
    left-toolbar="home | undo redo clear | h bold italic strikethrough quote | ul ol table hr | link image code | save "
    :toolbar="backBar"
    :disabled-menus="[]"
    
    :autofocus="true"
    :include-level="[1,2,3,4,5,6]"
    @save="save"
    @upload-image="handleUploadImage"
    ></v-md-editor>
</template>

<style scoped>
</style>